core.ws = {};

core.ws.FrameHolder = function(config){
	this.init(config);
}

core.extendClass('core.ws.FrameHolder', 'core.Box');

//#ifdef DESKTOP
core.ws.FrameHolder.prototype.remove = function(){
    if(this.locked)
        return;
	if(!this.parent.instanceOf('core.SplittedPanel'))
		return;
	var parent = this.parent;
	var neighbour = parent.getNeighbour(this);
//	core.log('me is: ', this.name, 'neighbour:', neighbour.name, 'parent:', parent.className, parent.className);
	if(!neighbour)
		return;
    this.workspace.unRegisterFrameHolder(this);
	parent.parent.replaceChild(parent, neighbour, core.REPLACE_CHILD_HIDE);
	if(this.workspace.root==parent){
		this.workspace.root = neighbour;
	}
	parent.destroy();
	this.destroy();
	neighbour.parent.refresh(true);

    core.desktop.app.sendMessage('holderRemoved', {
        workspace: this.workspace.name,
        holder: this.name
    });
}

core.ws.FrameHolder.prototype.split = function(aVertical, aUseRight){
	var panel = new core.SplittedPanel({
		workspace: this.workspace,
		vertical: aVertical
	});	
	var p = this.parent;
	this.parent.replaceChild(this, panel, core.REPLACE_CHILD_KEEP);
    if(aUseRight)
        panel.setRightElement(this);
    else
        panel.setLeftElement(this);
	var newPanel = new core.ws.FrameHolder({
		workspace: this.workspace
	});
    this.workspace.registerFrameHolder(newPanel);
    if(aUseRight)
        panel.setLeftElement(newPanel);
    else
        panel.setRightElement(newPanel);
	newPanel.updateLayout();
//	core.log('parent: ', this.parent.parent.className);
	p.refresh(true);
	if(this.workspace.root==this){
		this.workspace.root = panel;
	}

    core.desktop.app.sendMessage('holderSplitted', {
        holder: this.name,
        vertical: aVertical,
        right: aUseRight,
        splitterID: panel.name,
        holderID: newPanel.name,
        workspace: this.workspace.name
    });

    return newPanel;
}
//#endif

core.ws.FrameHolder.prototype.showFrame = function(aFrame, aRefresh){
//    core.log('showFrame: ws:', this.workspace.name,
//            'fr:', aFrame.title, 'vis:', this.isVisible());
	for(var i = 0; i<this.frames.length; i++){
		var f = this.frames[i];
		if(f==aFrame){
            var vis = this.isVisible();
            if(!vis){
            }else{
                this.replaceChild(this.items[1], aFrame, core.REPLACE_CHILD_HIDE);
                aFrame.show();
            }
            for(var j = 0; j<this.tabs.tabs.length; j++){
                var t = this.tabs.tabs[j];
                if(t.frame==aFrame){
                    this.tabs.selectTab(t);
                    break;
                }
            }
            if(f!=this.activeFrame){
//                core.log('sending frameSelected frame:', aFrame.jsFrame.code, this.name, this.workspace.name);
//#ifdef DESKTOP
                core.desktop.app.sendMessage('frameSelected', {
                    holder: this.name,
                    workspace: this.workspace.name,
                    frame: aFrame.dynamic? aFrame.jsFrame.instanceID:aFrame.jsFrame.code
                });
//#endif
            }
			this.activeFrame = aFrame;
//            core.log('showFrame', this.instanceID, aFrame.title);
//            if(aRefresh)
            if(vis){
//#ifdef DESKTOP
                this.refresh(aRefresh);
//#endif
//#ifdef MOBILE
                core.desktop.refreshDesktop();
//#endif
                aFrame.fire('show');
            }
			return true;
		}
	}
	return false;
}

//#ifdef DESKTOP
core.ws.FrameHolder.prototype.markAsDropTarget = function(aDropable){
    if(!this.framePosDiv){
        this.framePosDiv = core.newDiv(this.div, 'frame_pos');
    }
    return this.superCall('markAsDropTarget', arguments, aDropable);
}

core.ws.FrameHolder.prototype.unmarkAsDropTarget = function(){
//    core.log('Unmarking as drop target');
    if(this.framePosDiv){
        $(this.framePosDiv).remove();
        this.framePosDiv = null;
    }
    return this.superCall('unmarkAsDropTarget', arguments);
}

core.ws.FrameHolder.prototype.getDropTarget = function(aDraggable, aX, aY){
	if(!aDraggable.frame)
		return this.superCall('getDropTarget', arguments, aDraggable, aX, aY);
//	for(var i = 0; i<this.frames.length; i++){
//		var f = this.frames[i];
//		if(f==aDraggable.frame)
//			return null;
//	}
//    core.log('getDropTarget', aX, aY);
    var widthPart = aX/this.bounds.width;
    var heightPart = aY/this.bounds.height;
    var xPos = widthPart<0.25?0:widthPart>0.75?2:1;
    var yPos = heightPart<0.25?0:heightPart>0.75?2:1;
    this.xPos = xPos;
    this.yPos = yPos;
    if(!this.framePosDiv){
        this.framePosDiv = core.newDiv(this.div, 'frame_pos');
    }
    if(xPos==1 && yPos==1){
        $(this.framePosDiv).width(this.bounds.width-2*core.FRAME_POSITION_PADDING);
        $(this.framePosDiv).height(this.bounds.height-2*core.FRAME_POSITION_PADDING);
        this.alignBlock(this.framePosDiv, this.bounds.width, this.bounds.height, 'center', 'middle');
    }else{
        if(xPos!=1){
            $(this.framePosDiv).width(Math.floor(this.bounds.width/2));
            $(this.framePosDiv).height(this.bounds.height-2*core.FRAME_POSITION_PADDING);
        }else{
            $(this.framePosDiv).width(this.bounds.width-2*core.FRAME_POSITION_PADDING);
            $(this.framePosDiv).height(Math.floor(this.bounds.height/2));
        }
        this.alignBlock(this.framePosDiv, this.bounds.width, this.bounds.height,
                xPos==2?'right':'left', yPos==2?'bottom':'top', core.FRAME_POSITION_PADDING, core.FRAME_POSITION_PADDING);
    }
	return this;
}

core.ws.FrameHolder.prototype.acceptDraggable = function(aDraggable){
	var frame = aDraggable.frame;
	var frameHolder = aDraggable.frameHolder;
	if(!frame)
		return null;
    if(frameHolder.workspace==this.workspace)
        frameHolder.removeFrame(frame);
    if(this.xPos==1 && this.yPos==1){
        this.addFrame(frame);
        $(frame.div).appendTo(this.div);
    //	this.tabs.selectTab(frame.tab);
    }else{
        var vertical = this.xPos!=1;
        var useRight = vertical?this.xPos==0:this.yPos==0;
        var fh = this.split(vertical, useRight);
        fh.addFrame(frame);
        $(frame.div).appendTo(fh.div);
    }
    this.tabs.refresh();
    return true;
}
//#endif

core.ws.FrameHolder.prototype.setFrameTitle = function(aFrame, aTitle, aIcon){
	for(var i = 0; i<this.frames.length; i++){
		var f = this.frames[i];
		if(f==aFrame){
            aFrame.title = aTitle;
            aFrame.icon = aIcon;
			for(var j = 0; j<this.tabs.tabs.length; j++){
				var t = this.tabs.tabs[j];
				if(t.frame==aFrame){
					t.setText(aTitle, aIcon);
					return;
				}
			}
        }
    }
};

core.ws.FrameHolder.prototype.removeFrame = function(aFrame, aSilent){
	for(var i = 0; i<this.frames.length; i++){
		var f = this.frames[i];
		if(f==aFrame){
			for(var j = 0; j<this.tabs.tabs.length; j++){
				var t = this.tabs.tabs[j];
				if(t.frame==aFrame){
					this.tabs.removeTab(t);
					break;					
				}
			}
//			core.log('removing', aFrame.tab, 'from', this.tabs, this.tabs.tabs.length);
			if(this.tabs.tabs.length==0){
				this.replaceChild(this.items[1], this.body, core.REPLACE_CHILD_HIDE);				
				this.tabs.addTab(this.noFramesTab);
				this.tabs.selectTab(this.noFramesTab);
			}
            if(!aFrame.dynamic && !aSilent){
                for (var j = 0; j < this.frameCodes.length; j++) {
                    if(this.frameCodes[j]==aFrame.code){
                        this.frameCodes.splice(j, 1);
                        break;
                    }
                }
            }
			this.frames.splice(i, 1);
			this.refresh();

            if(!aSilent){
                core.desktop.app.sendMessage('frameRemoved', {
                    workspace: this.workspace.name,
                    holder: this.name,
                    frame: aFrame.dynamic?aFrame.jsFrame.instanceID:aFrame.jsFrame.code
                });
            }
			return true;
		}
	}	
	return false;
}

core.ws.FrameHolder.prototype.addFrame = function(aFrame){
    core.log('addFrame', this.tabs.instanceID);
	for(var i = 0; i<this.frames.length; i++){
		var f = this.frames[i];
		if(f==aFrame)
			return false;
	}
    if(!aFrame.dynamic){
        var found = false;
        for (var i = 0; i < this.frameCodes.length; i++) {
            if(this.frameCodes[i]==aFrame.code){
                found = true;
                break;
            }
        }
        if(!found)
            this.frameCodes.push(aFrame.code);
    }
	this.frames.push(aFrame);
	var tab = new core.Tab({
		text: aFrame.title || 'Untitled',
        icon: aFrame.icon,
//		menu: this.noFramesMenu,
        closeable: aFrame.parentWorkspace!=this.workspace || aFrame.jsFrame.closeable
	});
    var instance = this;
    tab.on('close', function(){
        if(aFrame.parentWorkspace!=instance.workspace)
            instance.removeFrame(this.frame);
        else{
            aFrame.jsFrame.requestClose();
        }
    });

	tab.frame = aFrame;
	tab.frameHolder = this;
	if(tab.dd && this.workspace && !this.workspace.floating){
		tab.enableDragging(desktop, tab.caption);
	}
	this.tabs.addTab(tab);
//	if(this.frames.length==1){
//		this.showFrame(aFrame);
//	}
	if(this.tabs.removeTab(this.noFramesTab)){
//        core.log('noFramesTab removed');
    }else{
//        core.log('noFramesTab not removed')
    }
    this.tabs.refresh();

//#ifdef DESKTOP
    core.desktop.app.sendMessage('frameAdded', {
        workspace: this.workspace.name,
        holder: this.name,
        frame: aFrame.dynamic? aFrame.jsFrame.instanceID:aFrame.jsFrame.code
    });
//#endif

	return true;
}

core.ws.FrameHolder.prototype.init = function(config){
	var instance = this;
    this.locked = config.locked;
	this.xType = 'frameholder';
	this.workspace = config.workspace;
	this.name = config.name || ('fh'+(core.idInc++));
//	core.log('fh', this.name);
	this.frames = [];
    this.frameCodes = $.makeArray(config.frameCodes);
	this.noFramesMenu = [
		{
//			text: 'Split vertically',
//			handler: function(){
//				instance.split(true);
//				return true;
//			}
//		},{
//			text: 'Split horizontally',
//			handler: function(){
//				instance.split(false);
//				return true;
//			}
//		},{
			text: 'Remove this',
			handler: function(){
				instance.remove();
				return true;
			}
		}
	];
    if(this.locked)
        this.noFramesMenu = null;
	
	this.noFramesTab = new core.Tab({
		text: 'No elements',
        align: 'center',
		menu: this.noFramesMenu
	});
	
	this.tabs = new core.Tabs({
		topDown: true,
		elements: this.noFramesTab
	});
    this.tabs.on('select', function(i, e, tab){
        if(tab && tab.frame){
            instance.showFrame(tab.frame, true);
//#ifdef DESKTOP
            if(e.mouse)
                tab.frame.body.focus();
//#endif
            return false;
        }
       return true;
    });
	this.body = new core.Panel({
	});
	this.reParent(this.body);
	this.reParent(this.tabs);
	
	this.superCall('init', arguments, {
		columns: '1',
		rows: 'd, 1',
        padding: 0,
        colspan: config.colspan,
		items: [this.tabs, this.body]
	});
    $(this.div).addClass('frameHolderDIV');
    this.padding = 0;
}

core.ws.Frame = function(config){
	this.init(config);
}

core.extendClass('core.ws.Frame', 'core.Box');

core.ws.Frame.prototype.getBody = function(){
	return this.body;
}

core.ws.Frame.prototype.getMinWidth = function(){
	var minWidth = this.superCall('getMinWidth', arguments);
	return minWidth;
}

core.ws.Frame.prototype.updateStatus = function(aStatus){
    if(this.status){
        this.statusLine.setText(aStatus);
        this.statusLine.refresh();
    }
}

core.ws.Frame.prototype.addToolbar = function(aToolbar){
    for (i = 0; i < this.toolbars.length; i++) {
        if(this.toolbars[i]==aToolbar)
            return false;
    }
    this.toolbars.push(aToolbar);

	var rows = '1';
	var items = [];
    for (i = 0; i < this.toolbars.length; i++) {
        items.push(this.toolbars[i]);
        rows = 'd,'+rows;
    }

	items.push(this.body);
    if(this.status){
        items.push(this.statusLine);
        rows += ',d';
    }
    this.setContent(items, '1', rows);
    return true;
}

core.ws.Frame.prototype.init = function(config){
	this.code = config.code;
	this.xType = 'frame';
	this.parentWorkspace = config.parentWorkspace;
	this.title = config.title;
    this.icon = config.icon;
	var instance = this;
	this.toolbars = [];
	var items = [];
	var rows = '1';
    this.closeable = config.closeable;
    this.dynamic = config.dynamic;
	jQuery.each(jQuery.makeArray(config.toolbar), function(i, e){
		if(e.instanceOf('core.Tabs')){
			instance.toolbars.push(e);
			items.push(e);
			rows = 'd,'+rows;
		}
	});
	var scrollable = true;
//#ifdef MOBILE
    scrollable = false;
//#endif
	this.body = new core.Panel({
		scrollable: scrollable,
		items: config.items,
		columns: config.columns,
		rows: config.rows
	});
	
	items.push(this.body);
    this.status = config.status;
//    core.log('this.status', this.status);
    if(this.status){
        this.statusLine = new core.OneLineHelper({
            text: ' '
        });
        items.push(this.statusLine);
        rows += ',d';
    }
	this.superCall('init', arguments, {
		columns: '1',
		rows: rows,
        padding: 0,
		items: items
	});
    $(this.div).addClass('frameDIV');
    this.updateLayout();
    this.componentVisible = false;
}

//#ifdef DESKTOP
core.ws.Workspace = function(config){
	this.init(config);
}

core.extendClass('core.ws.Workspace', 'core.Class');

core.ws.Workspace.prototype.showFrames = function(){	
    for(var i = 0; i<this.frameHolders.length; i++){
        var fh = this.frameHolders[i];
        fh.show();
        if(fh.activeFrame){
            fh.showFrame(fh.activeFrame);
        }
    }
}

core.ws.Workspace.prototype.getFrameHolder = function(aName){
    for(var i = 0; i<this.frameHolders.length; i++){
        var fh = this.frameHolders[i];
        if(fh.name==aName)
            return fh;
    }
	return null;
}

core.ws.Workspace.prototype.hasFrame = function(aFrame){
    for(var i = 0; i<this.frameHolders.length; i++){
        var fh = this.frameHolders[i];
        for(var j = 0; j<fh.frames.length; j++){
            if(fh.frames[j]==aFrame)
                return true;
        }
    }
    return false;
}
core.ws.Workspace.prototype.registerFrameHolder = function(aFrameHolder){
    for(var i = 0; i<this.frameHolders.length; i++){
        if(this.frameHolders[i]==aFrameHolder)
            return false;
    }
    this.frameHolders.push(aFrameHolder);
    return true;
}

core.ws.Workspace.prototype.unRegisterFrameHolder = function(aFrameHolder){
    for(var i = 0; i<this.frameHolders.length; i++){
        if(this.frameHolders[i]==aFrameHolder){
            this.frameHolders.splice(i, 1);
            return true;
        }
    }
    return false;
}

core.ws.Workspace.prototype.init = function(config){
	this.xType = 'ws';
	this.name = config.name || ('ws'+(core.idInc++));
    this.caption = config.caption || this.name;
	this.frameHolders = [];
    this.closeable = config.closeable;
	this.superCall('init', arguments, config);
	this.root = new core.ws.FrameHolder({
        name: this.name+'-root',
		workspace: this
	});
    this.root.hide();
    this.registerFrameHolder(this.root);
	this.root.updateLayout();
}

core.ws.Workspace.prototype.setRoot = function(aRoot){
    if(!aRoot)
        return;
    this.unRegisterFrameHolder(this.root);
    this.root = aRoot;
};
//#endif
